package com.junjie.checkin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junjie.checkin.entity.TReceiverAddress;
import com.junjie.checkin.exception.OperationsBeyondPermissionException;
import com.junjie.checkin.exception.ResourceNotFountException;
import com.junjie.checkin.mapper.AddressMapper;
import com.junjie.checkin.request.address.AddressRequest;
import com.junjie.checkin.response.address.AddressResponse;
import com.junjie.checkin.security.service.AuthDetails;
import com.junjie.checkin.security.service.JwtService;
import com.junjie.checkin.security.service.impl.JwtServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 洪浚杰
 * @description 地址服务
 * @date 2025/6/17 12:42
 */
@Service
public class AddressService {

    @Autowired
    private JwtServiceImpl jwtService;
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 插入地址
     * @param token 令牌
     * @param addressRequest 地址请求
     */

    public AddressResponse insertAddress(String token,AddressRequest addressRequest) {
        Integer id = jwtService.analyzeToken(token).getUser().getId();
        TReceiverAddress newAddress = new TReceiverAddress();
        // 获取地址列表
        List<TReceiverAddress> addressList = addressMapper.selectList(new QueryWrapper<TReceiverAddress>().eq("user_id", id));
        // 检查地址是否为首条数据,当为首条数据时,设置其为默认
        if (addressList == null|| addressList.isEmpty()){
            newAddress.setDefault(true);
        }
        else {
            // 如果不是首条数据,且这个新添加的数据为默认地址,则将原先的默认地址取消
            if (addressRequest.isDefaulted()){
                clearDefault();
            }
        }
        BeanUtils.copyProperties(addressRequest,newAddress);

        newAddress.setUserId(id);
        newAddress.setDefault(addressRequest.isDefaulted());
        addressMapper.insert(newAddress);
        AddressResponse response = new AddressResponse();
        BeanUtils.copyProperties(newAddress,response);
        response.setDefaulted(newAddress.isDefault());
        return response;

    }

    /**
     *  查看地址列表
     * @param token 用户token
     * @return 地址列表
     */

    public List<AddressResponse> getAllAddress(String token){
        AuthDetails details = jwtService.analyzeToken(token);
        List<TReceiverAddress> addresses = addressMapper.selectList(new QueryWrapper<TReceiverAddress>().eq("user_id", details.getUser().getId()));
        return addresses.stream().map(address -> {
            AddressResponse response = new AddressResponse();
            BeanUtils.copyProperties(address,response);
            response.setDefaulted(address.isDefault());
            return response;
        }).toList();
    }

    /**
     * 修改地址
     * @param addressRequest 修改地址信息
     * @param token 令牌
     * @param id 地址id
     */
    public void updateAddress(AddressRequest addressRequest,String token,Integer id){
        Integer userId = jwtService.analyzeToken(token).getUser().getId();
        TReceiverAddress address = addressMapper.selectById(id);
        // 检查地址是否存在
        if (Objects.isNull(address)){
            throw new ResourceNotFountException();
        }
        // 检查地址是否属于当前用户
        if (!address.getUserId().equals(userId)){
            throw new OperationsBeyondPermissionException();
        }
        // 检查是否为默认地址
        if (addressRequest.isDefaulted()){
            addressMapper.clearDefault();
        }
        BeanUtils.copyProperties(addressRequest,address);
        address.setDefault(addressRequest.isDefaulted());
        addressMapper.updateById(address);
    }

    public void deleteAddress(String token,Integer id){
        Integer userId = jwtService.analyzeToken(token).getUser().getId();
        TReceiverAddress address = addressMapper.selectById(id);
        // 检查地址是否存在
        if (Objects.isNull(address)){
            throw new ResourceNotFountException();
        }
        // 检查地址是否属于当前用户
        if (!address.getUserId().equals(userId)){
            throw new OperationsBeyondPermissionException();
        }
        addressMapper.deleteById(address);
    }
    /**
     * 清除默认地址
     */
    private  void clearDefault(){
        addressMapper.clearDefault();
    }





}
